import React from 'react';
import { connect } from 'dva';
import {Link} from 'dva/router'
import { Drawer,Flex ,List, NavBar,Icon, InputItem ,Picker, TabBar,Pagination ,Toast ,Button,Checkbox,WhiteSpace} from 'antd-mobile';
import { createForm } from 'rc-form'
import style from '../../style/App.less'
import Reset from '../../style/ResetInput.less'
import NavStyle from '../../style/ResNav.less'
import reqwest from 'reqwest';
import {numvail} from '../../utils/Validator.js'
const AgreeItem = Checkbox.AgreeItem;
class Login extends React.Component{
	constructor(props){
		super(props);
		this.state={
      radio:'Account',
      code:'发送验证码',
      timer:60,
		}
	}
  codeServer(){
    const {reg_phone} =this.state;
    const {getFieldValue} = this.props.form;
    // if()
    // console.log(getFieldValue('logphone'))
      // return
    reqwest({
      url: window.host+'/api/valid_codes',
      method: 'post',
      crossOrigin: true,
      type: 'json',
      data:{mobile:getFieldValue('logphone').replace(/\s+/g, "")},

    }).then((data) => {
      console.log(data);
      if(data.status=='success'){
        Toast.success(data.msg,0.5,()=>{},)
      }else{
        Toast.fail(data.msg,0.5)
      }
    }).fail((err,msg)=>{
      message.fail(err,0.5)
    });
  }
	loadServer(_data={}){
    const {radio} =  this.state;
		// console.log(data)
		reqwest({
      url: window.host+'/api/registrations',
      method: 'post',
      crossOrigin: true,
      type: 'json',
      data:{user:{name:_data.userName,mobile:_data.logphone.replace(/\s+/g, ""),password:_data.password},
        account:{name:_data.priseName,type:radio},
        valid_code:_data.code
      },
    }).then((data) => {
      if(data.status=='success'){
          let set ={"mobile":data.current_user.mobile,"avatar":data.current_user.avatar,"avatar_url":data.current_user.avatar_url,"name":data.current_user.name,"role":data.current_user.role,"accout_name":data.current_user.account.name,"invit_url":data.current_user.account.invit_url}
          Toast.success(
          '注册成功，将直接前往首页',
          1,
          ()=>{
              // window.location.hash=window.location.hash
            window.localStorage['token']=data.token;
            window.localStorage['curloe']=data.current_user.role;
            // debugger
            window.localStorage['menu']=JSON.stringify(data.menu);
            window.localStorage['cgj_id']=data.current_user.cgj_user_id;
            window.localStorage['account_type']=data.current_user.account_type;
            window.localStorage['userrr_id']=data.current_user.id;
            window.localStorage['setting']=JSON.stringify(set);
            // console.log(data.wallet)
            window.localStorage['money'] = JSON.stringify(data.current_user.wallet)
            window.localStorage['companies']=JSON.stringify(data.companies);
            window.sessionStorage['material']=JSON.stringify(data.materials);
            window.sessionStorage['store_tree']=JSON.stringify(data.stores_tree);
            window.location.hash='/hfive/home';
          }
        )
        
      }else{
        Toast.fail(
          data.msg,
          1
        )
      }
    }).fail( (err, msg) =>{
       Toast.offline('网络连接失败!!!', 1);
    });
	}
	handleSubmit(e){
		e.preventDefault();
    let _this =this;
    this.props.form.validateFields((err, values) => {
      console.log(!err);
      if (!err) {
        this.loadServer(values)
      }
    });
	}
  handleCodeClick(){
    let _this = this;
    let _timer = this.state.timer;
    console.log(this.props.form.getFieldError('logphone'))
    // return
    if(this.state.code=='发送验证码'&&this.props.form.getFieldError('logphone')==undefined&&this.props.form.getFieldValue('logphone')!=undefined){
      if(_timer==60){
        _this.codeServer()
        _this.setState({code:'60秒后重发'})
      }
      this.timeoutId = setInterval(() => {
        _timer--
        // _this.setState({timer:_timer});
        if(_this.state.timer>0){
            _this.setState({code:_timer +'秒后重发',timer:_timer})
            console.log(1)
          }else if(_this.state.timer<=0){
            _this.setState({code:'发送验证码',timer:60})
            clearInterval(_this.timeoutId)
          }
        }, 1000) 
    }else{
      this.props.form.setFields({
        logphone:{
          value:this.props.form.getFieldValue('logphone'),
          errors:[new Error('请输入手机号')]
        }
      })
    }
  }
  onChange(value,i){
    console.log(i);
    this.setState({radio:i.value})
  }
  componentWillMount(){
    clearInterval(this.timeoutId)
  }
  componentWillUnmount() {
    clearInterval(this.timeoutId)
  }
	render(){
    const _data = [{
      label:'品牌商',
      value:'Account'
    },{
      label:'经销商',
      value:'Dealer'
    }]
		 const { getFieldProps,getFieldError } = this.props.form;
		 return(
			<div>
				<NavBar style={{height:'1rem',background:'#3dbd7d',fontSize:'0.36rem'}} className={`${NavStyle.tel_nav}`} iconName={false} leftContent={<Link className={`${style.white}`} to={{pathname:'/log'}}><Icon type="left"  style={{marginBottom:'-0.1rem',}}  />登录</Link>}  onLeftClick={()=>{window.location.hash='/log'}} >注册管家快销</NavBar>
        <WhiteSpace size='lg' />
        <WhiteSpace size='lg' />
				<List >
          <InputItem
          className={`${Reset.tel_input}`}
            {...getFieldProps('logphone',{
              rules:[{required:true,message:'请输入手机号',len:11,validator:(rule,value,callback)=>{
                !!value?numvail(rule,value.replace(/\s+/g, ""),callback):callback('请输入手机号码')
              }}]
            })}
            type="phone"
            error={!!getFieldError('logphone')}
            onErrorClick={() => {
              alert(getFieldError('logphone').join('、'));
            }}
          >手机号码</InputItem>
           <InputItem
           className={`${Reset.tel_input}`}
           error={!!getFieldError('code')}
            onErrorClick={() => {
              alert(getFieldError('code').join('、'));
            }}
            {...getFieldProps('code',{
              rules:[{required:true}]
            })}
            placeholder="验证码"
          extra={<span onClick={this.handleCodeClick.bind(this)} style={{display:'block',fontSize:'0.28rem'}}>{this.state.code}</span>}
          >验证码</InputItem>
          <InputItem
          className={`${Reset.tel_input}`}
          error={!!getFieldError('userName')}
            onErrorClick={() => {
              alert(getFieldError('userName').join('、'));
            }}
            {...getFieldProps('userName',{
              rules:[{required:true}]
            })}
            type='text'
            placeholder="姓名"
          >姓名</InputItem>
          <InputItem
          className={`${Reset.tel_input}`}
          error={!!getFieldError('password')}
            onErrorClick={() => {
              alert(getFieldError('password').join('、'));
            }}
            {...getFieldProps('password',{
              rules:[{required:true}]
            })}
            type="password"
            placeholder="****"
          >密码</InputItem>
          <InputItem
          className={`${Reset.tel_input}`}
          error={!!getFieldError('priseName')}
            onErrorClick={() => {
              alert(getFieldError('priseName').join('、'));
            }}
            {...getFieldProps('priseName',{
              rules:[{required:true}]
            })}
          >企业名称</InputItem>
        </List>
        <List className={`${Reset.tel_list_header}`} renderHeader={()=>'企业类型'}>
        <Flex>
          <Flex.Item>
            {_data.map((i,index) => (
              <AgreeItem  key={i.value} data-seed={index} checked={i.value === this.state.radio} className={`${Reset.label} ${Reset.tel_radio}`} onChange={(e) =>{this.onChange(index,i) }}>
                {i.label}
              </AgreeItem>
            ))}
          </Flex.Item>
          </Flex>
        </List>
        <Button className={`${Reset.btn_moblie} ${Reset.tel_btn}`} onClick={this.handleSubmit.bind(this)}  type='primary'>注册</Button>
			</div>
	 	)
		
	}
}
        // <Link to={{pathname:'/log'}} style={{fontSize:'0.38rem'}}>登录</Link>

const LoginForm = createForm()(Login);

export default connect()(LoginForm)